﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class Admin_Image_Manager : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		//检查用户权限
		if (Session["Uid"] == null)
		{//无权限返回登录页
			Response.Redirect("AD_login.aspx");
			return;
		}
		//情况消息框
		lblMessage.Text = "";
		//如果页面第一次加载
		if (!IsPostBack)
		{
			LoadImage(1);
		}

	}
	protected void btnOK_Click(object sender, EventArgs e)
	{
		if (fldImg.HasFile)
		{
			string fileName = fldImg.FileName;
			if (System.IO.Path.GetExtension(fileName) == ".jpg" )
			{
				try
				{

					//指定上传文件在服务器上的保存路径 
					string savePath = Server.MapPath("~/UploadFiles/Five/");
					//检查服务器上是否存在这个物理路径，如果不存在则创建 
					if (!System.IO.Directory.Exists(savePath))
					{
						//需要注意的是，需要对这个物理路径有足够的权限，否则会报错 
						//另外，这个路径应该是在网站之下，而将网站部署在C盘却把上传文件保存在D盘 
						System.IO.Directory.CreateDirectory(savePath);
					}
					savePath = savePath + "\\" + ddlIndex.SelectedItem.Value + ".jpg"; 
					fldImg.SaveAs(savePath);//保存文件 
				
					fileName = ddlIndex.SelectedItem.Value + ".jpg"; 
					if (SaveImage(int.Parse(ddlIndex.SelectedItem.Value), txtWords.Text, txtAddress.Text, fileName))
					{
						lblMessage.Text = "成功";
						imgShow.ImageUrl = "~/UploadFiles/Five/" + fileName;
					}
					else
					{
						lblMessage.Text = "失败";
					}

				}
				catch
				{

				}
			}
			else {
				lblMessage.Text = "只允许上传jpg格式图片";
			}
		}
	}
	protected void btnCancel_Click(object sender, EventArgs e)
	{

	}
	/// <summary>
	/// iimID int PRIMARY KEY,--ID
	//	iimTitle nvarchar(40) NOT NULL,--显示名称
	//iimUrl nvarchar(40) NOT NULL DEFAULT('default.png')---地址
	/// </summary>
	/// <param name="id"></param>
	protected void LoadImage(int id)
	{
		string sql = "select * from Index_Image  where iimID=@id";
		SqlParameter[] paras = new SqlParameter[] { 
				new SqlParameter("@id",id)
			};
		DataTable dt = DataAccess.GetDataTable(sql, paras);

		imgShow.ImageUrl ="~/UploadFiles/Five/"+dt.Rows[0]["iimName"].ToString();
		txtWords.Text = dt.Rows[0]["iimTitle"].ToString();
		txtAddress.Text = dt.Rows[0]["iimUrl"].ToString();
	}
	private bool SaveImage(int id,string title,string url,string name)
	{
		string sql = "update Index_Image set iimTitle=@title,iimUrl=@url,iimName=@name where iimID=@id";
		SqlParameter[] paras = new SqlParameter[]{
			new SqlParameter("@title",title),
			new SqlParameter("@url",url),
			new SqlParameter("@name",name),
			new SqlParameter("@id",id)
		};

		bool result= DataAccess.ExecuteSQL(sql, paras);
		return result;
	}
	protected void ddlIndex_SelectedIndexChanged(object sender, EventArgs e)
	{
		LoadImage(int.Parse(ddlIndex.SelectedItem.Value));
	}
}